package org.zfes.snowier.zbss.xzy.router.user.live;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.TreeMap;
import java.util.UUID;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.zfes.snowier.common.eventpub.SimpleSubcriber;
import org.zfes.snowier.common.socket.data.MsgData;
import org.zfes.snowier.common.socket.device.sender.INettyMsgSender;
import org.zfes.snowier.common.socket.enums.TcpEventTopic;
import org.zfes.snowier.core.data.DataSet;
import org.zfes.snowier.web.controller.BaseController;
import org.zfes.snowier.web.util.FileResInfo;
import org.zfes.snowier.web.util.UploadUitl;
import org.zfes.snowier.xyz.live.Cmd;
import org.zfes.snowier.xyz.live.ILiveRequestManager;
import org.zfes.snowier.xyz.live.IVideoStatusManager;
import org.zfes.snowier.xyz.live.dto.LiveStatus;
import org.zfes.snowier.xyz.live.utils.LiveParamUtil;
import org.zfes.snowier.zbss.xzy.base.HosConst;
import org.zfes.snowier.zbss.xzy.biz.message.model.Message;
import org.zfes.snowier.zbss.xzy.biz.message.service.IMessageService;
import org.zfes.snowier.zbss.xzy.biz.vedio.model.CloudImage;
import org.zfes.snowier.zbss.xzy.biz.vedio.service.ICloudImageService;
import org.zfes.snowier.zbss.xzy.biz.vedio.service.ICloudVedioService;
import org.zfes.snowier.zbss.xzy.message.MessageInfoDto;
import org.zfes.snowier.zbss.xzy.vedio.LiveParamDto;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;

import io.swagger.annotations.ApiOperation;

import org.zfes.snowier.core.data.SelectVo;
import org.zfes.snowier.core.util.UUIDUtil;
import org.zfes.snowier.core.util.ZAssert;
import org.zfes.snowier.core.util.ZStrUtil;
import org.zfes.snowier.core.util.encypt.RSAUtil;
@Controller("org.zfes.snowier.zbss.xzy.router.user.live.VedioLiveWsController") 
@RequestMapping("/api/user/live/ws")
public class VedioLiveWsController implements BaseController {

	
	@Autowired
	private IMessageService messageService;

	@Autowired
	private ICloudVedioService cloudVedioService;
	
	@Autowired
	private ICloudImageService cloudImageService;
	
	@Autowired INettyMsgSender nettyMsgSender;
	
	@Autowired IVideoStatusManager videoStatusManager;
	
	@Autowired ILiveRequestManager liveRequestManager;
	
	
	@Value("${live.live-server:}")
	private String liveServer;
	@Value("${live.appid:}")
	private String liveAppId;
	@Value("${live.secret-id:}")
	private String liveSecretId;
	@Value("${live.asym-private-key:}")
	private String liveAsymPrivateKey;
	

//	Map<String,>
		 
	  @ApiOperation(value = "")
	  @RequestMapping(value="/loadVideoUrl/{deviceNum}/{channelId}/{requestId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	  public  @ResponseBody Object loadVideoUrl(
			  @PathVariable("deviceNum") String deviceNum,
			  @PathVariable("channelId") String channelId,
			  @PathVariable("requestId") String requestId){
		  ZAssert.hasText(deviceNum, "设备编号不能为空");
		  ZAssert.hasText(channelId, "通道不能为空");
		  ZAssert.hasText(channelId, "requestId不能为空");
//		if(true) {
//			return ajaxQuery("liveUrl", "http://47.92.196.10:8080/live/xz2.flv");
//		}
		  
		  Optional<LiveStatus>  liveStatusOp = videoStatusManager.getLiveChannelStatus(deviceNum, channelId);
		  ZAssert.notEmpty(liveStatusOp, "直播数据未准备好");
		  ZAssert.equals(Byte.valueOf("1"),liveStatusOp.get().getStatus(), "直播数据未准备好");
		  
		  String liveId=liveStatusOp.get().getLiveId();
		  
		  System.out.println("--loadVideoUrl--deviceNum:"+deviceNum+"||channelId:"+channelId+"||requestId:"+requestId+"||liveId:"+liveId);
			 
		 String us=UUIDUtil.fastUUID();
		 String t=""+System.currentTimeMillis();
		 String expire=""+System.currentTimeMillis()+60*1000;
		 //参数拼接
		 Map<String,String> params=  new ImmutableMap.Builder<String, String>()
				 			.put("liveId", liveId)
				            .put("appId", liveAppId)
				            .put("us", us)
				            .put("t", t)
				            .put("exp", expire)
				            .put("secretId", liveSecretId)
				            .build();
		
		//参数排序按照key的ascii码
	    String sortedDataToSign = LiveParamUtil.sortUrlParm(params);
	    System.out.println("sortedDataToSign:"+sortedDataToSign);
	    String sign=RSAUtil.sign(sortedDataToSign.getBytes(), liveAsymPrivateKey, true);
			
	    String dataToReq=liveId+".flv?appId="+liveAppId+"&us="+us+"&t="+t+"&exp="+expire+"&sign="+sign+"";
	    
	    //String dataToReq=liveId+".flv";
	    
	    String liveUrl=liveServer.endsWith("/")? liveServer+dataToReq : liveServer+"/"+dataToReq;
	    System.out.println("liveUrl:"+liveUrl);
		 return ajaxQuery("liveUrl", liveUrl);
		 
		 
	  }
	 
	  //线程1 检测<deviceNum_chid,Set<request>> //空的发送停止直播命令
	  @ApiOperation(value = "")
	  @RequestMapping(value="/liveRequestHeartBeat/{deviceNum}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	  public  @ResponseBody Object liveRequestHeartBeat(@PathVariable("deviceNum") String deviceNum, @RequestBody Map<String,String> data){
		  ZAssert.hasText(deviceNum, "设备编号不能为空");
		 // System.out.println("liveRequestHeartBeat-data:"+data);
//		  liveRequestManager.onRequestHeatBeat(deviceNum, channelId, requestId);
		  if(data!=null&&!data.isEmpty()) {
			  data.entrySet().forEach(en->{
				  liveRequestManager.onRequestHeatBeat(deviceNum, en.getKey(), en.getValue());
			  });
		  }
		  return ajaxDoneSuccess("ok");
	  }
	  
	  
	  @ApiOperation(value = "")
	  @RequestMapping(value="/startLive/{deviceNum}/{channelId}/{requestId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	  public  @ResponseBody Object startLive(
			  @PathVariable("deviceNum") String deviceNum,
			  @PathVariable("channelId") String channelId,
			  @PathVariable("requestId") String requestId
			  ){
		  System.out.println("--startLive--deviceNum:"+deviceNum+"||channelId:"+channelId+"||requestId:"+requestId);
		  ZAssert.hasText(deviceNum, "设备编号不能为空");
		  ZAssert.hasText(channelId, "通道不能为空");
		 
		  liveRequestManager.onRequestHeatBeat(deviceNum, channelId, requestId);

		  
		 String msgId = UUIDUtil.fastUUID();
		 nettyMsgSender.sendToDevice(deviceNum, 
	    			MsgData.ok()
	    			.setCmdCode(Cmd.startLive)
	    			.setCmdDirect(Byte.valueOf("1"))
	    			.setCmdUid(msgId)
	    			.setDeviceNum(deviceNum)
	    			.put("channelId", channelId)
	    			.put("deviceNum", deviceNum));
		  
		 return ajaxDoneSuccess("播放命令已发送");
	  }
	  
    
	  //<deviceNum_channelId，Set<requestId>>
	  @ApiOperation(value = "")
	  @RequestMapping(value="/stopLive/{deviceNum}/{channelId}/{requestId}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	  public  @ResponseBody Object stopLive(
			  @PathVariable("deviceNum") String deviceNum,
			  @PathVariable("channelId") String channelId,
			  @PathVariable("requestId") String requestId){
		  System.out.println("--stopLive--deviceNum:"+deviceNum+"||channelId:"+channelId+"||requestId:"+requestId);
			 
		  ZAssert.hasText(deviceNum, "设备编号不能为空");
		  ZAssert.hasText(channelId, "通道不能为空");
		  ZAssert.hasText(requestId, "requestId不能为空");
		  
		  liveRequestManager.onRequestDead(deviceNum,channelId,requestId);
		  
		 return ajaxSuccess();
	  }
	  
//		
//	  SimpleSubcriber.newIns()
//		.regist(TcpEventTopic.cmd_ack.getValue(),val->{
//			//如果收到命令确认
//			System.out.println("-cmd_ack-val:{"+val+"}");
//		},e->{
//			System.out.println("-cmd_ack- error："+e.getException().getMessage());
//		});
}